package com.stone.stoneanswer.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stone.stoneanswer.annotation.AuthCheck;
import com.stone.stoneanswer.common.BaseResponse;
import com.stone.stoneanswer.common.DeleteRequest;
import com.stone.stoneanswer.common.ErrorCode;
import com.stone.stoneanswer.common.ResultUtils;
import com.stone.stoneanswer.constant.UserConstant;
import com.stone.stoneanswer.exception.BusinessException;
import com.stone.stoneanswer.exception.ThrowUtils;
import com.stone.stoneanswer.model.dto.questionbank.QuestionBankAddRequest;
import com.stone.stoneanswer.model.dto.questionbank.QuestionBankGetRequest;
import com.stone.stoneanswer.model.dto.questionbank.QuestionBankRecommendRequest;
import com.stone.stoneanswer.model.dto.questionbank.QuestionBankUpdateRequest;
import com.stone.stoneanswer.model.entity.Question;
import com.stone.stoneanswer.model.entity.QuestionBank;
import com.stone.stoneanswer.model.entity.QuestionBankQuestion;
import com.stone.stoneanswer.model.entity.User;
import com.stone.stoneanswer.model.enums.UserRoleEnum;
import com.stone.stoneanswer.model.vo.QuestionBankVO;
import com.stone.stoneanswer.model.vo.QuestionVO;
import com.stone.stoneanswer.service.QuestionBankService;
import com.stone.stoneanswer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/questionBank")
@Slf4j
public class QuestionBankController {

    @Resource
    private QuestionBankService questionBankService;

    @Resource
    private UserService userService;

    // region 增删改查
    /**
     * 添加（仅管理员）
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestionBank(@RequestBody QuestionBankAddRequest questionBankAddRequest, HttpServletRequest request) {
        if (questionBankAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 构造要插入的数据
        // 创建时间和修改时间使用的是数据库中的默认值，即当前时间
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankAddRequest , questionBank);
        List<String> tags = questionBankAddRequest.getTags();
        if(tags!=null){
            questionBank.setTags(JSONUtil.toJsonStr(tags));
        }
        User loginUser = userService.getLoginUser(request);
        questionBank.setUserId(loginUser.getId());
        questionBank.setThumbNum(0);
        questionBank.setFavourNum(0);

        // 插入数据
        boolean result = questionBankService.save(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        Long newId = questionBank.getId();
        return ResultUtils.success(newId);
    }

    /**
     * 删除（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestionBank(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 返回是否删除成功
        boolean result = questionBankService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 删除（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteBatchQuestionBank(@RequestBody DeleteRequest deleteRequest ) {
        if (deleteRequest == null || deleteRequest.getIds() == null || deleteRequest.getIds().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(questionBankService.deleteBatchQuestionBank(deleteRequest));
    }

    /**
     * 更新（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBank(@RequestBody QuestionBankUpdateRequest questionBankUpdateRequest) {
        // 参数校验
        if (questionBankUpdateRequest == null || questionBankUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 判断要更新的数据是否存在
        long id = questionBankUpdateRequest.getId();
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank==null , ErrorCode.NOT_FOUND_ERROR);

        // 构建更新用的对象
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankUpdateRequest , questionBank);
        List<String> tags = questionBankUpdateRequest.getTags();
        if (tags != null) {
            questionBank.setTags(JSONUtil.toJsonStr(tags));
        }

        // 更新数据
        boolean result =questionBankService.updateById(questionBank);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<QuestionBankVO> getQuestionBankVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = questionBankService.getById(id);
        if (questionBank == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionBankService.getQuestionBankVO(questionBank, request));
    }

    /**
     * 分页获取
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionBankVO>> listQuestionBankVOByPage(@RequestBody QuestionBankGetRequest questionBankGetRequest,
            HttpServletRequest request) {
        long current = questionBankGetRequest.getCurrent();
        long size = questionBankGetRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankGetRequest));
        //规范化返回值
        return ResultUtils.success(questionBankService.getQuestionBankVOPage(questionBankPage, request));
    }

    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionBank>> listQuestionBankByPage(@RequestBody QuestionBankGetRequest questionBankGetRequest) {
        long current = questionBankGetRequest.getCurrent();
        long size = questionBankGetRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankGetRequest));
        //规范化返回值
        return ResultUtils.success(questionBankPage);
    }

    @PostMapping("/list")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<QuestionBank>> listQuestionBank(@RequestBody QuestionBankGetRequest questionBankGetRequest) {
        QueryWrapper<QuestionBank> queryWrapper = questionBankService.getQueryWrapper(questionBankGetRequest);
        List<QuestionBank> list = questionBankService.list(queryWrapper);
        return ResultUtils.success(list);
    }
    // endregion

    @PostMapping("/list/vo/recommend")
    public BaseResponse<Page<QuestionBankVO>> listQuestionBankVOByRecommend(@RequestBody QuestionBankRecommendRequest questionBankRecommendRequest, HttpServletRequest request) {
        try {
            userService.getLoginUser(request);
        } catch (Exception e) {
            QuestionBankGetRequest getRequest = new QuestionBankGetRequest();
            BeanUtil.copyProperties(questionBankRecommendRequest , getRequest);
            return listQuestionBankVOByPage(getRequest , request);
        }

        return ResultUtils.success(questionBankService.listQuestionBankVOByRecommend(questionBankRecommendRequest , request));
    }
}
